<template>
    <div class="layerPublicStyle">
        <lay-form-item label="商户名称" class="_row_style">
            <div class="_content">
                {{  formData.store_name }}
            </div>
        </lay-form-item>
        <lay-form-item label="合计金额" class="_row_style">
            <div class="_content">
                {{  formData.total_amount_yuan }} 元
            </div>
        </lay-form-item>
        <lay-form-item label="冻结金额" class="_row_style">
            <div class="_content">
                {{  formData.freeze_amount_yuan }} 元
            </div>
        </lay-form-item>
        <lay-form-item label="可用金额" class="_row_style">
            <div class="_content">
                {{  formData.available_amount_yuan }} 元
            </div>
        </lay-form-item>
        <lay-form-item label="钱包操作">
            <lay-radio v-model="formData.type" name="action" @change="radioChange" :value="0" label="加款"></lay-radio>
            <lay-radio v-model="formData.type" name="action" @change="radioChange" :value="1" label="扣款"></lay-radio>
            <lay-radio v-model="formData.type" name="action" @change="radioChange" :value="2" label="划转"></lay-radio>
        </lay-form-item>
        <lay-form-item :label="`钱包${lableToggle[formData.type]}`" v-if="formData.type!==2">
            <lay-select v-model="formData.wallet_select_type" placeholder="请选择">
                <lay-select-option :value="0" label="冻结金额"></lay-select-option>
                <lay-select-option :value="1" label="可用金额"></lay-select-option>
            </lay-select>
        </lay-form-item>
        <lay-form-item :label="`钱包${lableToggle[formData.type]}`" v-else>
            <lay-select v-model="formData.wallet_select_type" placeholder="请选择">
                <lay-select-option :value="2" label="冻结金额 => 可用金额"></lay-select-option>
                <lay-select-option :value="3" label="可用金额 => 冻结金额"></lay-select-option>
            </lay-select>
        </lay-form-item>
        <lay-form-item :label="`${lableToggle[formData.type]}金额`" class="_row_style">
            <div class="_content">
                <lay-input v-model="formData.input_money" type="number" :max="10000" :min="0"></lay-input>
                <div class="bar_text_tips">元</div>
            </div>
        </lay-form-item>

        <lay-form-item label="动态密码" class="_row_style">
            <div class="_content">
                <lay-input v-model="formData.user_token" type="text"  placeholder="请输入6位动态密码" :maxlength="6"></lay-input>
            </div>
        </lay-form-item>
        

    </div>
</template>

<script setup>
import {checkMoneyAmount} from '@/utils/helper.js'
import { reactive,nextTick,onMounted,ref} from 'vue'
import BigJs from 'big.js'
const foodTakeoutManage = uniCloud.importObject(`food-takeout-manage`, {customUI: true});


const db = uniCloud.database()

const props = defineProps({
    serverData:Object,
    callback:Function
})

    const { merchant_money_amount,store_name,_id:merchantId } =props.serverData;
    const { available_amount,freeze_amount } = merchant_money_amount || {}
    const available_amount_verify = available_amount || 0;      // 避免出现undefied的情况
    const freeze_amount_verify = freeze_amount || 0;      // 避免出现undefied的情况
    // 可用金额元
    const available_amount_yuan = +new BigJs( available_amount_verify ).div(100)
    // 冻结金额元
    const freeze_amount_yuan = +new BigJs( freeze_amount_verify ).div(100)
    // 合计金额元
    const total_amount_yuan = +new BigJs(available_amount_yuan).plus(freeze_amount_yuan)

    const lableToggle=reactive({
        0:`加款`,
        1:`扣款`,
        2:`划转`
    })
    const formData=reactive({
        store_name:store_name||``,
        available_amount_yuan,
        freeze_amount_yuan,
        total_amount_yuan,
        type:0,
        wallet_select_type:``,
        input_money:``,
        user_token:``
    })

    const transformToggle={
        0:(money_yuan)=>{     // 扣款 冻结金额
            if(money_yuan>freeze_amount_yuan){
                return {
                    errCode: 0,
                    myErrCode: 10001,
                    errMsg: '【冻结金额】不足，无法扣款'
                }
            }
            // 减去扣款冻结金额后 转成分
            const freeze_amount_fen = +new BigJs(freeze_amount_yuan).minus(money_yuan).times(100)
            const available_amount_fen = +new BigJs(available_amount_yuan).times(100)
            return {
                errCode: 0,
                myErrCode: 0,
                data:{
                    freeze_amount_fen,
                    available_amount_fen,
                    confirm_text:`你确定为【冻结金额】扣款【${money_yuan}】元？`,
                    record:[
                        {
                            merchant_id:merchantId,
                            wallet_type:0,
                            trade_type:2,
                            change_before_amount:freeze_amount_verify,
                            changet_after_amount:freeze_amount_fen,
                            change_amount:+new BigJs(money_yuan).times(100),
                            real_get_amount:+new BigJs(money_yuan).times(100),
                            remark: `【系统】冻结金额 扣款：${money_yuan}元`
                        }
                    ]
                }
            }
        },
        1:(money_yuan)=>{     // 扣款 可用金额
            if(money_yuan>available_amount_yuan){
                return {
                    errCode: 0,
                    myErrCode: 10001,
                    errMsg: '【可用金额】不足，无法扣款'
                }
            }
            // 减去扣款可用金额后 转成分
            const available_amount_fen = +new BigJs(available_amount_yuan).minus(money_yuan).times(100)
            const freeze_amount_fen = +new BigJs(freeze_amount_yuan).times(100)
            return {
                errCode: 0,
                myErrCode: 0,
                data:{
                    available_amount_fen,
                    freeze_amount_fen,
                    confirm_text:`你确定为【可用金额】扣款【${money_yuan}】元？`,
                    record:[
                        {
                            merchant_id:merchantId,
                            wallet_type:1,
                            trade_type:2,
                            change_before_amount:available_amount_verify,
                            changet_after_amount:available_amount_fen,
                            change_amount:+new BigJs(money_yuan).times(100),
                            real_get_amount:+new BigJs(money_yuan).times(100),
                            remark: `【系统】可用金额 扣款：${money_yuan}元`
                        }
                    ]
                }
            }
        },
        2:(money_yuan)=>{     // 划转  冻结金额 => 可用金额  
            if(money_yuan>freeze_amount_yuan){
                return {
                    errCode: 0,
                    myErrCode: 10001,
                    errMsg: '【冻结金额】不足，无法划转'
                }
            }
            // 减去扣款冻结金额后 转成分
            const freeze_amount_fen = +new BigJs(freeze_amount_yuan).minus(money_yuan).times(100)
            // 可用金额 加上划转的钱 转成分
            const available_amount_fen = +new BigJs(available_amount_yuan).plus(money_yuan).times(100)

            return {
                errCode: 0,
                myErrCode: 0,
                data:{
                    freeze_amount_fen,
                    available_amount_fen,
                    confirm_text:`你确定划转【${money_yuan}】元，【冻结金额 => 可用金额】？`,
                    record:[
                        {
                            merchant_id:merchantId,
                            wallet_type:0,
                            trade_type:2,
                            change_before_amount:freeze_amount_verify,
                            changet_after_amount:freeze_amount_fen,
                            change_amount:+new BigJs(money_yuan).times(100),
                            real_get_amount:+new BigJs(money_yuan).times(100),
                            remark: `【系统】冻结金额 => 可用金额 冻结金额扣款：${money_yuan}元`
                        },
                        {
                            merchant_id:merchantId,
                            wallet_type:1,
                            trade_type:3,
                            change_before_amount:available_amount_verify,
                            changet_after_amount:available_amount_fen,
                            change_amount:+new BigJs(money_yuan).times(100),
                            real_get_amount:+new BigJs(money_yuan).times(100),
                            remark: `【系统】冻结金额 => 可用金额 可用金额充值：${money_yuan}元`
                        }
                    ]
                }
            }
        },
        3:(money_yuan)=>{     // 划转  可用金额 => 冻结金额
            if(money_yuan>available_amount_yuan){
                return {
                    errCode: 0,
                    myErrCode: 10001,
                    errMsg: '【可用金额】不足，无法划转'
                }
            }
            // 减去 可用金额 后 转成分
            const available_amount_fen = +new BigJs(available_amount_yuan).minus(money_yuan).times(100)
            // 冻结金额 加上划转的钱 转成分
            const freeze_amount_fen = +new BigJs(freeze_amount_yuan).plus(money_yuan).times(100)

            return {
                errCode: 0,
                myErrCode: 0,
                data:{
                    freeze_amount_fen,
                    available_amount_fen,
                    confirm_text:`你确定划转【${money_yuan}】元，【可用金额 => 冻结金额】？`,
                    record:[
                        {
                            merchant_id:merchantId,
                            wallet_type:1,
                            trade_type:2,
                            change_before_amount:available_amount_verify,
                            changet_after_amount:available_amount_fen,
                            change_amount:+new BigJs(money_yuan).times(100),
                            real_get_amount:+new BigJs(money_yuan).times(100),
                            remark: `【系统】可用金额 => 冻结金额 可用金额扣款：${money_yuan}元`
                        },
                        {
                            merchant_id:merchantId,
                            wallet_type:0,
                            trade_type:3,
                            change_before_amount:freeze_amount_verify,
                            changet_after_amount:freeze_amount_fen,
                            change_amount:+new BigJs(money_yuan).times(100),
                            real_get_amount:+new BigJs(money_yuan).times(100),
                            remark: `【系统】可用金额 => 冻结金额 冻结金额充值：${money_yuan}元`
                        }
                    ]
                }
            }
        },
        '00':(money_yuan)=>{     //加款 冻结金额
            const available_amount_fen = +new BigJs(available_amount_yuan).times(100)
            const freeze_amount_fen = +new BigJs(freeze_amount_yuan).plus(money_yuan).times(100)

            return {
                errCode: 0,
                myErrCode: 0,
                data:{
                    freeze_amount_fen,
                    available_amount_fen,
                    confirm_text:`你确定为【冻结金额】加款【${money_yuan}】元？`,
                    record:[
                        {
                            merchant_id:merchantId,
                            wallet_type:0,
                            trade_type:3,
                            change_before_amount:freeze_amount_verify,
                            changet_after_amount:freeze_amount_fen,
                            change_amount:+new BigJs(money_yuan).times(100),
                            real_get_amount:+new BigJs(money_yuan).times(100),
                            remark: `【系统】冻结金额 充值：${money_yuan}元`
                        },
                    ]
                }
            }
        },
        '01':(money_yuan)=>{         //加款 可用金额
            const available_amount_fen = +new BigJs(available_amount_yuan).plus(money_yuan).times(100)
            const freeze_amount_fen = +new BigJs(freeze_amount_yuan).times(100)
            
            return {
                errCode: 0,
                myErrCode: 0,
                data:{
                    freeze_amount_fen,
                    available_amount_fen,
                    confirm_text:`你确定为【可用金额】加款【${money_yuan}】元？`,
                    record:[
                        {
                            merchant_id:merchantId,
                            wallet_type:1,
                            trade_type:3,
                            change_before_amount:available_amount_verify,
                            changet_after_amount:available_amount_fen,
                            change_amount:+new BigJs(money_yuan).times(100),
                            real_get_amount:+new BigJs(money_yuan).times(100),
                            remark: `【系统】可用金额 充值：${money_yuan}元`
                        },
                    ]
                }
            }
        }
    }


    onMounted(async () => {
        props.callback([
            parentCallVerify
        ]);
    })

    async function radioChange(e){
        formData.wallet_select_type=``
    }

    function parentCallVerify(){
        return new Promise(async resolve=>{
            const input_money_str=formData.input_money+''
            const moneyResult =checkMoneyAmount(input_money_str)
            if(moneyResult.myErrCode!==0){
                return layer.msg(moneyResult.errMsg, { icon : 2, time: 1500})
            }
            if(formData.wallet_select_type===``){
                return layer.msg(`请先选择 【钱包${lableToggle[formData.type]}】 项`, { icon : 2, time: 1500})
            }
            if(formData.user_token.trim()==''){
                return layer.msg(`请先输入6位动态密码`, { icon : 2, time: 1500})
            }

            let computedMethod=null
            // 目前是金额正确的情况下
            if(formData.type!==0){
                // 在非加款的情况下 需要判断 操作金额是否小于指定钱包账户的钱
                if(formData.type===1||formData.type===2){  //扣款 划转
                    computedMethod =transformToggle[formData.wallet_select_type]
                    if(!computedMethod){
                        return layer.msg(`未知的操作方式，请联系管理员`, { icon : 2, time: 1500})
                    }
                }else{
                    return layer.msg(`未知的操作方式，请联系管理员`, { icon : 2, time: 1500})
                }
            }else{
                // 加款的情况下
                computedMethod= transformToggle[`0${formData.wallet_select_type}`]
            }
            const computedResult=computedMethod(moneyResult.data.amount)
            if(computedResult.myErrCode!==0){
                return layer.msg(computedResult.errMsg, { icon : 2, time: 1500})
            }
            const { confirm_text,...money_info }=computedResult.data
            const results= await new Promise((next)=>{
                layer.confirm(confirm_text, {
                    title:`操作提示`,
                    area:[`400px`,`170px`],
                    icon:3,
                    btn: [{
                        text:`确定`,
                        callback:async (layerId)=>{
                            next(1);
                            layer.close(layerId);
                        }
                    },{
                        text:`取消`,
                        callback:(layerId)=>{
                            next(0)
                            layer.close(layerId);
                        }
                    }]
                }) 
            }) 
            if(results===1){
                uni.showLoading({
                    title: `正在处理`,
                    mask:true
                });
                try {
                    const {myErrCode,errMsg}=await foodTakeoutManage.merchantWalletPlusMinus(merchantId,formData.user_token,money_info)
                    uni.hideLoading()
                    if(myErrCode!==0){
                        return layer.msg(errMsg, { icon : 2, time: 1500})
                    }
                    layer.msg(`处理成功`, { time: 1500,icon:1 })
                    resolve(1)
                } catch (error) {
                    console.error(error)
                    uni.hideLoading()
                    return layer.msg(`访问过于火爆，请稍后再试`, { icon : 2, time: 1500})
                }
            }
        })
    }

</script>

<style lang="stylus" scoped>
</style>


